<template>
  <PageContainer title="企业查询" :showBack="false">
    <div class="mb-4">
      <div>
        <a-auto-complete
          v-model="formQuery.qymc"
          style="width: 360px"
          placeholder="请输入企业名称"
          :data="gxOptions"
          button-text="搜索"
        />
        <a-button type="primary" @click="handleSearch2">搜索</a-button>
      </div>
    </div>
    <a-spin class="w-full" :loading="getTableLoading">
      <div v-if="!isEmpty && isFirst">
        <a-card>
          <div class="flex mb-4 justify-between items-center">
            <strong style="font-size: 20px">{{ formQuery.qymc }}</strong>
            <a-space>
              <a-tooltip>
                <template #content>
                  基于查询企业进项、销项的发票数据分析。<br />
                  进项是指售卖方，销项是指购买方，商品大<br />
                  类和小类名称是基于税务发票“货物名称”<br />
                  分类，数量、金额、税收都来源于发票信<br />
                  息。<br />
                </template>
                <icon-question-circle size="16" style="color: #A3B0CC" />
              </a-tooltip>
              <a-select v-model="formQuery.dl" :options="typeOptions" style="width: 216px" @change="handleSearch">
                <template #prefix>
                  分类筛选
                </template>
              </a-select>
              <a-button @click="handleDetail">数据分析</a-button>
            </a-space>
          </div>
          <div class="mb-4">
            <PanelCollapse :input-list="inputList" :output-list="outputList"></PanelCollapse>
          </div>
          <div>
            <a-table 
              :data="data"
              :columns="tableColumns"
              column-resizable
              :bordered="{ cell: true }"
              :loading="getTableLoading"
              :pagination="tablePagination"
              :scroll="{ x: '100%', y: '100%' }"
              @page-change="pageChange"
              @page-size-change="pageSizeChange"
            >
              <template #jxMc="{ record }">
                <div v-if="record?.jxMc" class="flex justify-between">
                  <div style="flex: 1; width: 0" v-tip>{{ record?.jxMc }}</div>
                  <a-tooltip :content="record.jxSfbdMc">
                    <a-tag color="blue" size="small">{{ record.jxSfbd }}</a-tag>
                  </a-tooltip>
                </div>
                <span v-else> - </span>
              </template>
              <template #xxMc="{ record }">
                <div v-if="record?.xxMc" class="flex justify-between">
                  <div style="flex: 1; width: 0" v-tip>{{ record?.xxMc }}</div>
                  <a-tooltip :content="record.xxSfbdMc">
                    <a-tag color="blue" size="small">{{ record.xxSfbd }}</a-tag>
                  </a-tooltip>
                </div>
                <span v-else> - </span>
              </template>
              <template #jxHwmcMc="{ record }">
                <div v-if="record?.jxHwmcMc" class="tag" :style="{ background: record.jxHwmcMcColor }" v-tip>
                  {{ record.jxHwmcMc }}
                </div>
                <span v-else> - </span>
              </template>
              <template #xxHwmcMc="{ record }">
                <div v-if="record?.xxHwmcMc" class="tag" :style="{ background: record.xxHwmcMcColor }" v-tip>
                  {{ record.xxHwmcMc }}
                </div>
                <span v-else> - </span>
              </template>
              <template #jxHwmcDl="{ record }">
                <div v-if="record?.jxHwmcDl" class="tag" :style="{ background: record.jxHwmcDlColor }" v-tip>
                  {{ record.jxHwmcDl }}
                </div>
                <span v-else> - </span>
              </template>
              <template #xxHwmcDl="{ record }">
                <div v-if="record?.xxHwmcDl" class="tag" :style="{ background: record.xxHwmcDlColor }" v-tip>
                  {{ record.xxHwmcDl }}
                </div>
                <span v-else> - </span>
              </template>
            </a-table>
          </div>
        </a-card> 
      </div>
      <div v-else style="padding-top: 200px" class="flex items-center">
        <a-empty description="暂无数据，查询企业后，将在此处展示查询结果"></a-empty>   
      </div>  
    </a-spin>
  </PageContainer>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import PageContainer from '@/components/PageContainer/index.vue';
import PanelCollapse from '@/components/PanelCollapse.vue';
import { useRouter } from 'vue-router';
import { formatWithThousandSeparator } from '@/utils';
import { getCpdlList, getQyJxPage, getQymcList, getJxjy, getXxjy } from '@/api/enterpriseInquiry';

const colors = ['#FFF0E5', '#FFF7E0', '#F0F4FA', '#E8FCE3', '#E5EFFE', '#4CD4F0', '#FFCAAF', '#FFC04D', '#53DB97', '#FFE45C', '#FDAA65', '#FE7F80']; 
const tags2 = [];
const isFirst = ref(false);
const router = useRouter();
const inputList = ref({
  label: '进项',
  list: []
});
const outputList = ref({
  label: '销项',
  list: []
});
const data = ref([]);
const typeOptions = ref([
  { label: '全部分类', value: '' }
]);
const formQuery = ref({
  qymc: '',
  dl: ''
});
const getTableLoading = ref(false);
const tableColumns = ref([
  {
    title: '进项',
    titleSlotName: 'input',
    headerCellStyle: {},
    children: [
      {
        title: '售卖方企业',
        dataIndex: 'jxMc',
        slotName: 'jxMc'
      },
      {
        title: '小类名称',
        dataIndex: 'jxHwmcMc',
        slotName: 'jxHwmcMc',
        ellipsis: true,
		    tooltip: true
      }, 
      {
        title: '类别',
        dataIndex: 'jxHwmcDl',
        slotName: 'jxHwmcDl'
      }, 
      {
        title: '金额',
        dataIndex: 'jxJe',
        align: 'right',
        ellipsis: true,
		    tooltip: true,
      },
      {
        title: '税收',
        dataIndex: 'jxSe',
        align: 'right',
        ellipsis: true,
		    tooltip: true,
      }
    ]
  },
  {
    title: '销项',
    titleSlotName: 'output',
    headerCellStyle: {},
    children: [
      {
        title: '购买方企业 ',
        dataIndex: 'xxMc',
        slotName: 'xxMc'
      },
      {
        title: '小类名称',
        dataIndex: 'xxHwmcMc',
        slotName: 'xxHwmcMc',
      }, 
      {
        title: '类别',
        dataIndex: 'xxHwmcDl',
        slotName: 'xxHwmcDl'
      }, 
      {
        title: '金额',
        dataIndex: 'xxJe',
        align: 'right',
        ellipsis: true,
		    tooltip: true,
      },
      {
        title: '税收',
        dataIndex: 'xxSe',
        align: 'right',
        ellipsis: true,
		    tooltip: true,
      }
    ]
  }
]);
const tablePagination = ref({
	total: 0,
	showTotal: true,
	showJumper: true,
	showPageSize: true,
	current: 1,
	pageSize: 10
});

const gxOptions = ref([]);

const isEmpty = computed(() => {
  return !!formQuery.value.qymc && !formQuery.value.dl && !data.value.length;
});

// 获取进项建议
function getInputList() {
  getJxjy({ qymc: formQuery.value.qymc }).then((res) => {
    inputList.value = { label: '进项', list: res };
  });
}

// 获取进项建议
function getOutputList() {
  getXxjy({ qymc: formQuery.value.qymc }).then((res) => {
    outputList.value = { label: '销项', list: res };;
  });
}

// 获取产品大类名称列表
function getCpdlListOptions() {
  getCpdlList().then((res) => {
    typeOptions.value = [
      ...typeOptions.value,
      ...res.map((item) => ({ value: item, label: item }))
    ]
  });
}

// 获取公司列表
function getGxOptions() {
  getQymcList().then((res) => {
    gxOptions.value = res;
  })
}

function getColor(list, mc) {
  let index = list.findIndex((item) => item === mc);
  if (index === -1 && mc) {
    list.push(mc);
    index = list.length - 1;
  }
  return colors[index % colors.length];
}



function getTableList() {
  getTableLoading.value = true;
  getQyJxPage({
    ...formQuery.value,
    pageNo: tablePagination.value.current,
    pageSize: tablePagination.value.pageSize
  }).then((res) => {
    const { records, total } = res;
    tablePagination.value.total = total;
    const list = [];
    for(const item of records) {
      const jxHwmcMc = item?.jx?.hwmcMc;
      const xxHwmcMc = item?.xx?.hwmcMc;
      const jxHwmcDl = item?.jx?.hwmcDl;
      const xxHwmcDl = item?.xx?.hwmcDl;
      const jxSfbd = item?.jx?.sfbd;
      const xxSfbd = item?.xx?.sfbd;
      const keys = {
        '异地': ['外', '外地企业'],
        '本地': ['内', '本地企业'],
      };
      const color = getColor(tags2, jxHwmcDl);
      const color2 = getColor(tags2, xxHwmcDl);
      list.push({ 
        ...item,
        jxMc: item?.jx?.mc,
        jxHwmcMc: jxHwmcMc,
        jxHwmcMcColor: color,
        jxSfbd: keys[jxSfbd]?.[0],
        jxSfbdMc: keys[jxSfbd]?.[1],
        jxHwmcDl,
        jxHwmcDlColor: color,
        jxJe: formatWithThousandSeparator(item?.jx?.je || 0),
        jxSe: formatWithThousandSeparator(item?.jx?.se || 0),
        xxMc: item?.xx?.mc,
        xxHwmcMc: xxHwmcMc,
        xxHwmcMcColor: color2,
        xxSfbd: keys[xxSfbd]?.[0],
        xxSfbdMc: keys[xxSfbd]?.[1],
        xxHwmcDl,
        xxHwmcDlColor: color2,
        xxJe: formatWithThousandSeparator(item?.xx?.je || 0),
        xxSe: formatWithThousandSeparator(item?.xx?.se || 0),
      });
    }
    data.value = list;
    isFirst.value = true;
  }).finally(() => {
    getTableLoading.value = false;
  });
}

function pageChange(val) {
	tablePagination.value.current = val;
	getTableList();
}
function pageSizeChange(val) {
	tablePagination.value.pageSize = val;
	getTableList();
}

function handleDetail() {
  router.push({ name: 'EnterpriseInquiryDetail', query: { qymc: formQuery.value.qymc } })
}

function handleSearch() {
  if (!formQuery.value.qymc) return;
  tablePagination.value.current = 1;
  getTableList();
  getInputList();
  getOutputList();
}

function handleSearch2() {
  formQuery.value.dl = '';
  handleSearch();
}

onMounted(() => {
  handleSearch();
  getGxOptions();
  getCpdlListOptions();
});
</script>

<style lang="less" scoped>
.tag {
  display: inline-block;
  max-width: 100%; 
  color: var(--color-text-2);
  padding: 1px 4px;
  font-size: 12px;
  border-radius: 4px;
}
</style>

<script>
export default {
  name: 'EnterpriseInquiry',
}
</script>